import { createStore } from 'vuex'

export default createStore({
    state: {
        user: (() => {
            try {
                const userData = localStorage.getItem('user');
                // 处理undefined/null/无效JSON的情况
                return userData && userData !== 'undefined'
                    ? JSON.parse(userData)
                    : null;
            } catch (e) {
                console.error('解析用户数据失败:', e);
                return null;
            }
        })
    },
    mutations: {
        SET_USER(state, user) {
            state.user = user
            localStorage.setItem('user', JSON.stringify(user))
        },
        CLEAR_USER(state) {
            state.user = null
            localStorage.removeItem('user')
        }
    },
    actions: {
        login({ commit }, user) {
            commit('SET_USER', user)
        },
        logout({ commit }) {
            commit('CLEAR_USER')
        }
    },
    getters: {
        currentUser: state => state.user,
        hasRole: state => role => state.user?.role === role
    }
})